package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     *
     * @param dto 申请信息
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //检查老人是否已经入住
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .eq(Elder::getStatus, 1)
        );
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new RuntimeException("老人已入住");
        }
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        //更新床位信息
        Bed bed = bedMapper.selectById(checkInConfigDto.getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增或更新老人
        elder = saveOrUpdate(elder, bed, dto);

        //新增入住信息
        CheckIn checkIn = saveCheckIn(dto, elder);
        //新增入住配置信息
        saveCheckInConfig(dto, checkIn);
        //新增合同信息
        saveContract(dto, elder);
    }

    /**
     * 查询入住详情
     * @param id 入住id
     * @return 入住详情
     */
    @Override
    @Transactional
    public CheckInDetailVo getCheckInById(Long id) {
        //根据id查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);
        //从入住信息中获取身份证号
        String idCard = checkIn.getIdCardNo();
        String birthYear, birthMonth, birthDay;
        //根据身份证号，得出出生日期
        if (idCard.length() == 18) {
            // 18位身份证：第7-14位为出生日期，格式为YYYYMMDD
            birthYear = idCard.substring(6, 10);
            birthMonth = idCard.substring(10, 12);
            birthDay = idCard.substring(12, 14);
        } else {
            // 15位身份证：第7-12位为出生日期，格式为YYMMDD（19XX年）
            birthYear = "19" + idCard.substring(6, 8);
            birthMonth = idCard.substring(8, 10);
            birthDay = idCard.substring(10, 12);
        }
        // 构建出生日期
        Date date = DateUtils.parseDate(birthYear + "-" + birthMonth + "-" + birthDay);
        //根据入住id获取入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, id));
        //根据身份证获取老人信息
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, checkIn.getIdCardNo()));
        //根据老人id获取合同信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        //构建老人信息返回类
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        //补全老人信息返回类的年龄
        checkInElderVo.setAge(DateUtils.differentDaysByMillisecond(date, new Date())/365);
        //构建家属信息返回类
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        //构建入住配置信息返回类
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        //补全入住配置信息返回类的入住时间和结束时间
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        //构建入住详情返回类
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //填充入住详情返回类
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }

    private void saveContract(CheckInApplyDto dto, Elder elder) {
        CheckInContractDto contractDto = dto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(contractDto, Contract.class);
        //补全老人信息
        contract.setElderId(Integer.valueOf(elder.getId().toString()));
        contract.setElderName(elder.getName());

        //借助工具类生成合同编码
        contract.setContractNumber(CodeGenerator.generateContractNumber());

        //获取开始时间与结束时间，并根据开始时间与当前时间的对比得到合同的状态
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(status);

        contractMapper.insert(contract);
    }

    private void saveCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn saveCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        //补全老人相关信息
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());

        //将家庭联系人转为JSON格式作为备注
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        String jsonStr = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(jsonStr);

        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        //调用mapper层方法向数据库添加
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private Elder saveOrUpdate(Elder oldElder, Bed bed, CheckInApplyDto dto) {
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder newElder = BeanUtil.toBean(checkInElderDto, Elder.class);
        newElder.setStatus(1);
        newElder.setBedId(bed.getId());
        newElder.setBedNumber(bed.getBedNumber());
        //若elder不为空，则为更新老人，若为空，则为新增老人
        if (ObjectUtil.isNotEmpty(oldElder)) {
            newElder.setId(oldElder.getId());
            elderMapper.updateById(newElder);
            return newElder;
        } else {
            elderMapper.insert(newElder);
            return newElder;
        }
    }
}
